import React, { Component } from 'react';
import Card from '@material-ui/core/Card';
import TextField from '@material-ui/core/TextField';
import Typography from '@material-ui/core/Typography';
import { Get, Post, PostWithSession, sleep, deepCopy, replaceAll, GetAsync} from './utility';
import { CardContent } from '@material-ui/core';
import router from 'umi/router';
import Button from '@material-ui/core/Button';
import { makeStyles } from '@material-ui/core/styles';
import Container from '@material-ui/core/Container';
import Grid from '@material-ui/core/Grid';
import CssBaseline from '@material-ui/core/CssBaseline';
import Avatar from '@material-ui/core/Avatar';
import LockOutlinedIcon from '@material-ui/icons/LockOutlined';

import { createMuiTheme, ThemeProvider } from '@material-ui/core/styles';
import orange from '@material-ui/core/colors/orange';


const theme = createMuiTheme({
  palette: {
    primary: orange,
  },
});

const Event = {};
Event.addEvents = function(target,eventType,handle){
  if(document.addEventListener){
      Event.addEvents = function(target,eventType,handle){
          target.addEventListener(eventType,handle,false);
      };
  }else{
      Event.addEvents = function(target,eventType,handle){
          target.attachEvent('on'+eventType,function(){
              handle.call(target,arguments);
          });
      };
  };
  Event.addEvents(target, eventType,handle);
};

const NetErrMsg = "出现异常, 请联系波比"
const InvalidInput = "无效输入"

const useStyles = makeStyles(theme => ({
  paper: {
    marginTop: theme.spacing(8),
    display: 'flex',
    flexDirection: 'column',
    alignItems: 'center',
  },
  avatar: {
    width:'80px',
    height:'80px',
  },
  form: {
    width: '100%', // Fix IE 11 issue.
    marginTop: theme.spacing(1),
  },
  submit: {
    margin: theme.spacing(3, 0, 2),
  },
}));



class Board extends Component {

  constructor(props) {
    super(props);
    this.state = {
       //user: "609869680",
      // pwd: "fish0618",
      user:localStorage.getItem("user") || "",
      pwd:"",
      score: "",
      token: "",
    }
  }

  initPage() {

  }

  componentWillMount() {
    this.initPage()
    Event.addEvents(document, "keydown",this.handleKeyDown);
    const token = localStorage.getItem("token")
    if (token){
      router.push("/swop")
    }
  }

  componentDidMount(){
  }

  componentWillUmount(){
    document.removeEventListener("keydown",this.handleKeyDown);
  }

  componentDidUpdate() {
  }

  edit = event => {
    this.state[event.target.name] = event.target.value
  }

  click = event => {
    // localStorage.setItem("score", 2313)
    // localStorage.setItem("userName", "Macbook")
    // localStorage.setItem("token", "708a1306a7012de070a0dd0061769f48")
    // router.push("/swop")
    // return
    // router.push("/swop")
    // return

    localStorage.setItem("user", this.state.user)

    if (this.state.user === "" || this.state.pwd === ""){
      alert(InvalidInput)
      return
    }

    GetAsync("login", {"userId": this.state.user, "userPassword": this.state.pwd}, function(resp){
      console.log(resp["token"])
      if (typeof(resp["token"]) === "undefined"){
        alert(resp.errMsg || NetErrMsg)
        return
      }

      const { errMsg, integral, userId, userName, token } = resp
      if (errMsg){
        alert(errMsg)
        return
      }

      localStorage.setItem("score", integral)
      localStorage.setItem("userId", userId)
      localStorage.setItem("userName", userName)
      localStorage.setItem("token", token)
      router.push("/swop")

    }, function(){
      alert('网络错误')
    })

  }

  handleKeyDown = (event) => {
    if(event.key === 'F12' || event.keyCode === 'F12'){
      event.preventDefault()
      window.event.returnValue = false;
      return (false)
    }
  }

  handleKeyPress = (event) => {

  }

  render() {
    const self = this
    function SignIn() {
      const classes = useStyles();

      return (
        <ThemeProvider theme={theme}>
        <Container component="main" maxWidth="xs">
          <CssBaseline />
          <div className={classes.paper}>
            <Avatar src={require('./images/loginAvatar.png')} className={classes.avatar}>

            </Avatar>
            <Typography component="h1" variant="h5">
              你懂的
            </Typography>
            <form className={classes.form} noValidate>
              <TextField
                variant="outlined"
                margin="normal"
                required
                fullWidth
                id="standard-basic"
                label="账号"
                name="user"
                autoComplete="user"
                autoFocus
                onChange={self.edit}
                defaultValue={self.state.user}
              />
              <TextField
                variant="outlined"
                margin="normal"
                required
                fullWidth
                name="pwd"
                label="密码"
                type="password"
                id="password"
                autoComplete="current-password"
                onChange={self.edit}
              />
              <Button
                type="button"
                fullWidth
                variant="contained"
                color="primary"
                className={classes.submit}
                onClick={self.click}
              >
                登录
              </Button>
            </form>
          </div>
        </Container>
        </ThemeProvider>
      );
    }

    return (
      <SignIn />


    )
  };
}

export default Board;
